package command.runtime;

import constant.Symbol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * 同步执行命令或脚本
 */
public class SynchronousLocalShellCommand {

    Logger log = LoggerFactory.getLogger(SynchronousLocalShellCommand.class);

    // 要执行的命令
    private final String command;

    public SynchronousLocalShellCommand(String command) {
        this.command = command;
    }

    public String execCommand() {
        Process process = null;
        String errorMessage = null;
        try {
            process = Runtime.getRuntime().exec(command);
        } catch (IOException e) {
            log.error("command:{},exception", command, e);
            errorMessage = e.getMessage();
        }

        // Process对象获取不成功时，返回错误信息
        if (process == null) {
            return errorMessage;
        }

        // 获取子进程的输入流，子进程的输入流从Process对象表示的进程的标准输出流获得
        String commandResponseOk = reader(process.getInputStream());

        // 进行错误信息的读取
        String commandResponseError = reader(process.getErrorStream());
        // 构建响应结果
        String commandResponse = commandResponseOk + Symbol.LINE + commandResponseError;
        int responseCode = -1;
        try {
            // 等待进程结束
            responseCode = process.waitFor();
        } catch (InterruptedException e) {
            log.error("run command:{} InterruptedException", command, e);
        }
        return commandResponse;
    }

    private String reader(InputStream inputStream) {
        String osName = System.getProperty("os.name");
        //不同平台使用的编码不一样
        String charset = osName.contains("Windows") ? "GBK" : "UTF-8";
        StringBuilder outData = new StringBuilder();
        try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName(charset));
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                outData.append(line);
                outData.append(Symbol.LINE);
            }
        } catch (IOException e) {
            log.error("command:{},exception", command, e);
        }
        return outData.toString();
    }
}
